<?php
/**
 * 字体后台管理
 *
 * 字体后台管理service
 *
 * @author    zhouchao <zhouchao@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */
namespace App\Services\FontService;
use Illuminate\Support\Facades\DB;
use App\Services\BaseService;
use App\Services\ImgServices\ImgTool;
use App\Services\ModifyResourcePriceRecordsService\ModifyResourcePriceRecordsService;
use Auth;

class FontBackService extends BaseService
{
    public function __construct(ImgTool $img_tool,ModifyResourcePriceRecordsService $modify_service)
    {
        $this->img_tool = $img_tool;
        $this->modify_service = $modify_service;
    }


    /**
     * 获取字体列表
     * @param int $per_page
     * @return mixed
     */
    public function get_font_list($per_page = 10){
        $this->setParameter([
            'table' => 'fonts',
            'where' => [['state','=',1]],
            'select'=> ['font_id','font_name','font_image','font_type','price','is_default','created_at']
        ]);
        $fonts = $this->getAllPaginated($per_page);
        foreach($fonts as $font){
            $font->font_image = env('IMG_URL_STD_PREFIX').$font->font_image;
        }
        return $fonts;
    }

    /**
     * 保存文件
     * @param $data
     * @return mixed
     */
    public function save_font($data){
        $img_path=$this->img_tool->imgSave($data['font_image'],2);
        if(!empty($img_path)){
            $data['font_image'] = $img_path;
        }else{
            return false;
        }
        $data['font_path'] = $this->saveFonts($data['font_path']);
        $data['created_at'] = $data['updated_at'] = time();
        $this->table = 'fonts';
        $flag = $this->save($data);
        return $flag;
    }

    /**
     * 修改
     * @param $data
     * @return bool
     */
    public function update_font($data){
        //根据ID获取字体
        $font = DB::table('fonts')->where('font_id',$data['font_id'])->first();
        if(empty($font)){
            return false;
        }
        if(isset($data['price'])){
            //更新价格 插入数据库修改价格记录
            $record_result = $this->modify_service->save_modify_resource_price_record(array('resource_type'=>3,'resource_id'=>$data['font_id'],'price'=>$font->price,'modify_price'=>$data['price'],
                'admin_id'=>Auth::user()->id,'admin_email'=>Auth::user()->email));
            if(empty($record_result)){
                return false;
            }
            unset($data['price']);//统一在晚上修改
        }
        if(!empty($data['font_path'])){
            $font_path = $this->saveFonts($data['font_path']);
            $data['font_path'] = $font_path;
        }
        if(!empty($data['font_image'])){
            $font_image = $this->img_tool->imgSave($data['font_image'],2);
            $data['font_image'] = $font_image;
        }
        $data['updated_at'] = time();
        $this->table = 'fonts';
        $this->where = [['font_id','=',$data['font_id']]];
        $flag = $this->update($data);
        return $flag;
    }

    /**
     * 删除
     * @param $font_id
     * @return mixed
     */
    public function remove_font($font_id)
    {
        $flag = DB::table('fonts')
            ->where('font_id', $font_id)
            ->update(['state' => 2,'updated_at'=>time()]);
        return $flag;
    }

    /**
     * 获取是否有在修改的价格
     * @param $font_id
     * @return bool
     */
    public function get_modify_price($font_id)
    {
        return ModifyResourcePriceRecordsService::is_resource_modify_price($font_id,0,3);
    }

    public function saveFonts($file)
    {
        if ($file != null) {
            //生成图片名
            $newName = md5(date('ymdhis') . rand(1, 1000)) . ".ttf";
            $folder = date('Ym', time());
            $folder_path = public_path('fonts/' . $folder);
            $this->mkFolder($folder_path);
            $file->move($folder_path, $newName);
            if (file_exists(public_path('fonts/' . $folder . '/' . $newName))) {
                //判断字体的唯一性
                $this->table = 'fonts';
                $font_paths = $this->pluck('font_path')->toArray();
                $font_paths = array_unique($font_paths);
                foreach ($font_paths as $font_path) {
                    if (file_exists(public_path('fonts/' . $font_path))) {
                        $m1 = md5_file(public_path('fonts/' . $folder . '/' . $newName));
                        $m2 = md5_file(public_path('fonts/' . $font_path));
                        if ($m1 == $m2) {
                            return $font_path;
                        }
                    }
                }
                return $folder . '/' . $newName;
            }
        }
        return false;
    }

    function mkFolder($path){
        if(is_dir($path)){//已经是目录了就不用创建
            return true;
        }
        if(is_dir(dirname($path))){//父目录已经存在，直接创建
            return mkdir($path);
        }
        $this->mkFolder(dirname($path));//从子目录往上创建
        return mkdir($path);//因为有父目录，所以可以创建路径
    }
}